//
//  DiyViewController.m
//  WallpaperHdLib
//
//  Created by 王朝孟 on 2021/3/2.
//


//// 网络视频搞不定
//NSString *imageStr = @"https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a4b3d7085dee3d6d2293d48b252b5910/0e2442a7d933c89524cd5cd4d51373f0830200ea.jpg";
//NSString *videoStr = @"http://vjs.zencdn.net/v/oceans.mp4";




#import "DiyViewController.h"

#import <Photos/Photos.h>
#import <PhotosUI/PhotosUI.h>


@interface DiyViewController ()

@property (nonatomic, strong) UIImageView *iv;
@property (nonatomic, strong) UIButton *button, *button2;
@property (nonatomic, strong) PHLivePhotoView *livePhotoView;

@end

@implementation DiyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.iv = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 150, 170)];
    self.iv.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.iv];
    
    self.livePhotoView = [[PHLivePhotoView alloc] initWithFrame:self.iv.frame];
    self.livePhotoView.contentMode = UIViewContentModeScaleAspectFill;
    self.livePhotoView.clipsToBounds = YES;
    [self.view addSubview:self.livePhotoView];
    
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button.frame = CGRectMake(100, 300, 100, 40);
    [self.button setTitle:@"download" forState:UIControlStateNormal];
    [self.button setBackgroundColor:[UIColor greenColor]];
    [self.view addSubview:self.button];
    [self.button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button2.frame = CGRectMake(100, 400, 100, 40);
    [self.button2 setTitle:@"save" forState:UIControlStateNormal];
    [self.button2 setBackgroundColor:[UIColor greenColor]];
    [self.view addSubview:self.button2];
    [self.button2 addTarget:self action:@selector(button2Action) forControlEvents:UIControlEventTouchUpInside];
    
}

- (PHAssetCollection *)getCurrentPhotoCollectionWithTitle:(NSString *)collectionName {
     
     // 1. 创建搜索集合
     PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
     
     // 2. 遍历搜索集合并取出对应的相册
     for (PHAssetCollection *assetCollection in result) {
         
         if ([assetCollection.localizedTitle containsString:collectionName]) {
             return assetCollection;
         }
     }
     
     return nil;
 }

// 保存图片
 - (void)saveImage:(UIImage *)image toCollectionWithName:(NSString *)collectionName {
     
     // 1. 获取相片库对象
     PHPhotoLibrary *library = [PHPhotoLibrary sharedPhotoLibrary];
     
     // 2. 调用changeBlock
     [library performChanges:^{
         
         // 2.1 创建一个相册变动请求
         PHAssetCollectionChangeRequest *collectionRequest;
         
         // 2.2 取出指定名称的相册
         PHAssetCollection *assetCollection = [self getCurrentPhotoCollectionWithTitle:collectionName];
         
         // 2.3 判断相册是否存在
         if (assetCollection) { // 如果存在就使用当前的相册创建相册请求
             collectionRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
         } else { // 如果不存在, 就创建一个新的相册请求
             collectionRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:collectionName];
         }
         
         // 2.4 根据传入的相片, 创建相片变动请求
         PHAssetChangeRequest *assetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
         
         // 2.4 创建一个占位对象
         PHObjectPlaceholder *placeholder = [assetRequest placeholderForCreatedAsset];
         
         // 2.5 将占位对象添加到相册请求中
         [collectionRequest addAssets:@[placeholder]];
         
     } completionHandler:^(BOOL success, NSError * _Nullable error) {
         
         // 3. 判断是否出错, 如果报错, 声明保存不成功
         if (error) {
            //  [SVProgressHUD showErrorWithStatus:@"保存失败"];
         } else {
             // [SVProgressHUD showSuccessWithStatus:@"保存成功"];
         }
     }];
 }

- (void)saveImage:(UIImage *)image assetCollectionName:(NSString *)collectionName {
     
     // 1. 获取当前App的相册授权状态
     PHAuthorizationStatus authorizationStatus = [PHPhotoLibrary authorizationStatus];
     
     // 2. 判断授权状态
     if (authorizationStatus == PHAuthorizationStatusAuthorized) {
         
         // 2.1 如果已经授权, 保存图片(调用步骤2的方法)
         [self saveImage:image toCollectionWithName:collectionName];
         
     } else if (authorizationStatus == PHAuthorizationStatusNotDetermined) { // 如果没决定, 弹出指示框, 让用户选择
         
         [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
             
             // 如果用户选择授权, 则保存图片
             if (status == PHAuthorizationStatusAuthorized) {
                 [self saveImage:image toCollectionWithName:collectionName];
             }
         }];
         
     } else {
         
         // [SVProgressHUD showWithStatus:@"请在设置界面, 授权访问相册"];
     }
 }




-(void)pictureClicked{
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    
    pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

//    pickerController.mediaTypes =@[@"kUTTypeMovie"];
    pickerController.mediaTypes = [NSArray arrayWithObjects:@"public.movie",  nil]; //picker中只显示视频
    pickerController.allowsEditing = YES;
    pickerController.delegate = self;
    
    [self.navigationController presentViewController:pickerController animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info{
    
    [picker dismissViewControllerAnimated:YES completion:nil];

    //这个是获取本地图库视频的路径
    NSURL *url = info[UIImagePickerControllerMediaURL];
    NSString *urlStr = [NSString stringWithFormat:@"%@",url];

    //获取本地视频的第一帧当作封面
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];

    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];

    assetGen.appliesPreferredTrackTransform = YES;

    CMTime time = CMTimeMakeWithSeconds(0.0, 600);

    NSError*error =nil;

    CMTime actualTime;

    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    

    //这个就是第一帧的图片了
    UIImage *videoImage = [[UIImage alloc]initWithCGImage:image];

//    _testimage.image = videoImage;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)buttonAction{

    [PHLivePhoto requestLivePhotoWithResourceFileURLs:@[[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"IMB_rz9Xy4" ofType:@"JPG"]], [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"IMB_rz9Xy4" ofType:@"mov"]]] placeholderImage:[UIImage imageNamed:@"IMB_rz9Xy4.JPG"] targetSize:self.livePhotoView.bounds.size contentMode:PHImageContentModeAspectFill resultHandler:^(PHLivePhoto * _Nullable livePhoto, NSDictionary * _Nonnull info) {
        self.livePhotoView.livePhoto = livePhoto;
    }];
}
- (void)button2Action{
//    [self save2WithPhotoUrl:[[NSBundle mainBundle] pathForResource:@"wp1" ofType:@"JPG"] videoUrl:[[NSBundle mainBundle] pathForResource:@"wp1" ofType:@"MOV"]];
//    [self save2WithPhotoUrl:[[NSBundle mainBundle] pathForResource:@"np" ofType:@"JPG"] videoUrl:[[NSBundle mainBundle] pathForResource:@"wp" ofType:@"MOV"]];
   
    // 本地视频可以搞定
    [self save2WithPhotoUrl:[[NSBundle mainBundle] pathForResource:@"IMB_rz9Xy4" ofType:@"JPG"] videoUrl:[[NSBundle mainBundle] pathForResource:@"IMB_rz9Xy4" ofType:@"mov"]];
    
//    // 网络视频搞不定
//    NSString *imageStr = @"https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a4b3d7085dee3d6d2293d48b252b5910/0e2442a7d933c89524cd5cd4d51373f0830200ea.jpg";
//    NSString *videoStr = @"http://vjs.zencdn.net/v/oceans.mp4";
//
//    [self save2WithPhotoUrl:imageStr videoUrl:videoStr];
}

- (void)save2WithPhotoUrl:(NSString *)photoURLstring videoUrl:(NSString *)videoURLstring{
    NSURL *photoURL = [NSURL fileURLWithPath:photoURLstring];//@"...picture.jpg"
    NSURL *videoURL = [NSURL fileURLWithPath:videoURLstring];//@"...video.mov"
    

//    [self saveImage:videoImage assetCollectionName:@"test"];

//    NSURL *photoURL = [NSURL URLWithString:photoURLstring];
//    NSURL *videoURL = [NSURL URLWithString:videoURLstring];
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetCreationRequest *request = [PHAssetCreationRequest creationRequestForAsset];
        [request addResourceWithType:PHAssetResourceTypePhoto
                             fileURL:photoURL
                             options:nil];
        [request addResourceWithType:PHAssetResourceTypePairedVideo
                             fileURL:videoURL
                             options:nil];
        
    } completionHandler:^(BOOL success,
                          NSError * _Nullable error) {
        if (success) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
            [alert show];
        } else {
            NSLog(@"error: %@",error);
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
            [alert show];
        }
    }];
}

@end
